package cn.icare.cms.controller.restful;

import cn.icare.cms.DateUtil;
import cn.icare.cms.ExcelWriter;
import cn.icare.cms.OrderService;
import cn.icare.cms.StringUtil;
import cn.icare.cms.model.ro.SearchOrderListRo;
import cn.icare.cms.model.ro.UpdateOrderSysMemoRo;
import cn.icare.cms.model.ro.UpdateSendStatusRo;
import cn.icare.cms.model.vo.rest.RespMsgVO;
import cn.icare.cms.qrcode.QRCodeUtil;
import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping(value = "/rest/order")
@Api(tags = "REST商品订单")
public class OrderController extends BaseController {
    @Resource
    private OrderService orderService;
    private final String FALL_STRING = "请求失败,服务繁忙!";

    @Value("${cms.upload.physical-path}")
    private String qrcodeSavePath;

    @Value("${cms.upload.web-path}")
    private String qrcodeSaveUrl;
    @Value("${cms.logo}")
    private String logoImgPath;

    /**
     * URL:http://{ip}:{port}/rest/order/{id}
     * method:DELETE
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @HystrixCommand(fallbackMethod = "deleteOneFall")
    @ApiOperation(value = "删除单个订单", notes = "t_order表删除符合主键的单个订单")
    public ResponseEntity<RespMsgVO> deleteOne(@PathVariable("id") Long id) {
        if (this.orderService.deleteOne(id)) {
            return super.getRespOk();
        } else {
            return super.getRespFail();
        }
    }

    /**
     * URL:http://{ip}:{port}/rest/order?ids={ids}
     * method:DELETE
     *
     * @param ids
     * @return
     */
    @DeleteMapping()
    @HystrixCommand(fallbackMethod = "deleteBatchFall")
    @ApiOperation(value = "删除多个订单", notes = "t_order表删除符合主键的多个订单")
    public ResponseEntity<RespMsgVO> deleteBatch(@RequestParam("ids") List<Long> ids) {
        if (this.orderService.deleteBatch(ids)) {
            return super.getRespOk();
        } else {
            return super.getRespFail();
        }
    }

    /**
     * URL:http://{ip}:{port}/rest/order/{id}
     * method:GET
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @HystrixCommand(fallbackMethod = "getOneFall")
    @ApiOperation(value = "查询单个订单", notes = "t_order表返回符合主键的单个订单")
    public ResponseEntity<RespMsgVO> getOne(@PathVariable("id") Long id) {
        return super.getRespOk(this.orderService.getDetail(id));
    }

    /**
     * URL:http://{ip}:{port}/rest/order?args={args}
     * method:GET
     *
     * @return
     */
    @PostMapping("/list")
    @HystrixCommand(fallbackMethod = "getListFall")
    @ApiOperation(value = "查询多个订单", notes = "user表返回符合条件的多个订单")
    public ResponseEntity<RespMsgVO> getList(@RequestBody SearchOrderListRo ro) {

        return super.getRespOk(this.orderService.getSysList(ro));
    }

    @PostMapping("/updateSendStatus")

    @ApiOperation(value = "更新订单开始发货状态", notes = "更新订单开始发货状态")
    public ResponseEntity<RespMsgVO> getList(@RequestBody UpdateSendStatusRo ro) {

        boolean result = this.orderService.updateSendStart(ro.getOrderId(), ro.getArrivalmemberId());
        if (result)
            return super.getRespOk();
        else
            return super.getRespFail("系统忙请稍候再试");

    }

    /**
     * URL:http://{ip}:{port}/rest/order/{id}
     * method:GET
     *
     * @param id
     * @return
     */
    @GetMapping("/qrcodeimage/{id}")
    @ApiOperation(value = "获取订单二维码图片url", notes = "获取订单二维码图片url")
    public ResponseEntity<RespMsgVO> getQrCodeImageUrl(@PathVariable("id") Long id) {

        String url = "";
        try {
            String filename = DateUtil.formateToDateTime(new Date(), "yyyy/MM") + "/" + id.toString() + ".jpg";

            //生成的二维码的路径及名称
            String savePath = this.qrcodeSavePath + "/" + filename;
            url = this.qrcodeSaveUrl + "/" + filename;
            // 存放在二维码中的内容
            String text = id.toString();
            // 嵌入二维码的图片路径
            String imgPath = this.logoImgPath;
            File file = new File(savePath);
            if (!file.exists()) {
                //生成二维码
                QRCodeUtil.encode(text, imgPath, savePath, true);
            }
            return super.getRespOk(url);
        } catch (Exception ex) {
            return super.getRespFail("二维码生成失败");
        }
    }


    /**
     * URL:http://{ip}:{port}/rest/order?args={args}
     * method:GET
     *
     * @return
     */
    @GetMapping("/export")
    @ApiOperation(value = "导出订单商品列表", notes = "导出订单商品列表")
    public ResponseEntity<RespMsgVO> exportOrderItemList(@RequestParam("beginTime") String beginTime,
                                                         @RequestParam("endTime") String endTime,
                                                         @RequestParam(value = "areaCode", required = false) String areaCode
    ) {

        List<Map<String, Object>> dataList = this.orderService.getExportItemList(beginTime, endTime, areaCode);
        if (dataList != null && dataList.size() > 0) {
            XSSFWorkbook workbook = null;
            OutputStream out = null;
            String url = "";
            boolean issuccess = false;
            String error = "";
            try {
                dataList.parallelStream().forEach(item -> {
                    if ("1".equals(item.get("type").toString())) {
                        item.put("type", "是");
                    } else {
                        item.put("type", "否");
                    }
                });
                String title = String.format("待发货商品列表(%s-%s)", beginTime, endTime);
                String[] headers = new String[]{"商品名称", "数量", "促销"};
                String[] columns = new String[]{"title", "num", "type"};
                String filename = "export/" + DateUtil.formateToDateTime(new Date(), "yyyy/MM/dd") + "/" + DateUtil.getCurrentDatetime() + ".xlsx";
                //生成的excel的路径及名称
                String savePath = this.qrcodeSavePath + "/" + filename;
                ExcelWriter<Map<String, Object>> excelWriter = new ExcelWriter<>();

                //在列表数据中增加总计一行
                long totalNum = 0;
                IntSummaryStatistics summaryStatistics = dataList.stream().mapToInt((x) -> Integer.valueOf(x.get("num").toString())).summaryStatistics();
                totalNum = summaryStatistics.getSum();
                Map mapTotal = new HashMap<>();
                mapTotal.put("title", "总计");
                mapTotal.put("num", totalNum);
                mapTotal.put("type", "");
                dataList.add(mapTotal);
                workbook = excelWriter.exportData(title, headers, columns, dataList);
                QRCodeUtil.mkdirs(savePath.substring(0, savePath.lastIndexOf("/")));
                out = new FileOutputStream(savePath);
                workbook.write(out);
                url = this.qrcodeSaveUrl + "/" + filename;
                issuccess = true;

            } catch (Exception ex) {
                ex.printStackTrace();
                error = "导出异常：" + ex.getMessage();
            } finally {
                try {
                    if (null != workbook) {
                        workbook.close();
                    }
                    if (null != out) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    error = "导出异常：" + e.getMessage();
                }
            }
            if (issuccess) {
                return super.getRespOk(url);
            } else {
                return super.getRespFail(error);
            }

        } else {
            return super.getRespFail("暂无数据");
        }
    }


    @PostMapping("/batchUpdateSend")

    @ApiOperation(value = "批量一键配送", notes = "批量一键配送")
    public ResponseEntity<RespMsgVO> batchUpdateSend(@RequestBody UpdateSendStatusRo ro) {

        boolean result = this.orderService.batchUpdateSend(ro.getArrivalmemberId());
        if (result)
            return super.getRespOk();
        else
            return super.getRespFail("系统忙请稍候再试");

    }


    @PostMapping("/updateSysMemo")
    @ApiOperation(value = "更新订单系统备注", notes = "更新订单系统备注")
    public ResponseEntity<RespMsgVO> updateSysMemo(@RequestBody UpdateOrderSysMemoRo ro, HttpServletRequest request) {


        if (ro.getOrderId() == null || StringUtil.isEmpty(ro.getSysMemo())) {
            return super.getRespFail("输入参参数不正确，参数内容：" + JSON.toJSONString(ro));
        }
        String systemUserName = getCurrentUserName(request);
        ro.setSysMemo(ro.getSysMemo() + " 修改人:" + systemUserName + " 修改时间:" + DateUtil.formateToDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"));

        boolean result = this.orderService.updateSysMemo(ro);
        if (result)
            return super.getRespOk();
        else
            return super.getRespFail("系统忙请稍候再试");

    }


    /**
     * URL:http://{ip}:{port}/rest/order?args={args}
     * method:GET
     *
     * @return
     */
    @GetMapping("/exportfinished")
    @ApiOperation(value = "导出已经发货订单列表", notes = "导出已经发货订单列表")
    public ResponseEntity<RespMsgVO> exportfinishedOrder(@RequestParam("beginTime") String beginTime,
                                                         @RequestParam("endTime") String endTime,
                                                         @RequestParam(value = "areaCode", required = false) String areaCode
    ) {

        List<Map<String, Object>> dataList = this.orderService.getFinishedList(beginTime, endTime, areaCode);
        if (dataList != null && dataList.size() > 0) {
            XSSFWorkbook workbook = null;
            OutputStream out = null;
            String url = "";
            boolean issuccess = false;
            String error = "";
            try {

                String title = "已发货订单列表";
                String[] headers = new String[]{"下单时间", "姓名", "联系电话", "地址", "金额"};
                String[] columns = new String[]{"createtime", "name", "mobile", "address", "ammount"};
                String filename = "export/" + DateUtil.formateToDateTime(new Date(), "yyyy/MM/dd") + "/" + DateUtil.getCurrentDatetime() + ".xlsx";
                //生成的excel的路径及名称
                String savePath = this.qrcodeSavePath + "/" + filename;
                ExcelWriter<Map<String, Object>> excelWriter = new ExcelWriter<>();

                //在列表数据中增加总计一行
                Double totalNum = 0d;

                DoubleSummaryStatistics summaryStatistics = dataList.stream().map(x -> Double.valueOf(x.get("ammount").toString()))
                        .collect(Collectors.summarizingDouble(value -> value));
                totalNum = summaryStatistics.getSum();


                Map mapTotal = new HashMap<>();
                mapTotal.put("createtime", "总计");
                mapTotal.put("name", "");
                mapTotal.put("mobile", "");
                mapTotal.put("address", "");
                mapTotal.put("ammount", totalNum);
                dataList.add(mapTotal);
                workbook = excelWriter.exportData(title, headers, columns, dataList);
                QRCodeUtil.mkdirs(savePath.substring(0, savePath.lastIndexOf("/")));
                out = new FileOutputStream(savePath);
                workbook.write(out);
                url = this.qrcodeSaveUrl + "/" + filename;
                issuccess = true;

            } catch (Exception ex) {
                ex.printStackTrace();
                error = "导出异常：" + ex.getMessage();
            } finally {
                try {
                    if (null != workbook) {
                        workbook.close();
                    }
                    if (null != out) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    error = "导出异常：" + e.getMessage();
                }
            }
            if (issuccess) {
                return super.getRespOk(url);
            } else {
                return super.getRespFail(error);
            }

        } else {
            return super.getRespFail("暂无数据");
        }
    }


    //#region fallback methods
    private ResponseEntity<RespMsgVO> deleteOneFall(Long id) {
        return super.getRespFail(this.FALL_STRING);
    }

    private ResponseEntity<RespMsgVO> deleteBatchFall(List<Long> ids) {
        return super.getRespFail(this.FALL_STRING);
    }

    private ResponseEntity<RespMsgVO> getOneFall(Long id) {
        return super.getRespFail(this.FALL_STRING);
    }

    private ResponseEntity<RespMsgVO> getListFall(SearchOrderListRo ro) {
        return super.getRespFail(this.FALL_STRING);
    }
    //#endregion

}
